const { AUTH_SESSION_NAME } = require("./consts")
import dayjs from '../dayjs.min'

function showLoading(title = '加载中') {
  wx.showLoading({
    title,
  })
}

function hideLoading() {
  wx.hideLoading()
}

function checkToken() {
  const res = wx.getStorageSync(AUTH_SESSION_NAME)
  if (res) {
    const date = dayjs(res['expire_date'])
    const diff = date.diff(dayjs(), 'minutes')
    return diff > 0
  }
  return false
}

/**
 * 保存token信息
 * @param {string} token
 * @param {string} date
 */
function saveToken(token, date) {
  wx.setStorageSync(AUTH_SESSION_NAME, {
    expire_date: date,
    access_token: token
  })
}

/**
 * 清除token信息
 */
function clearToken() {
  wx.removeStorageSync(AUTH_SESSION_NAME)
}

/**
 * 获取acess_token
 */
function getToken() {
  const res = wx.getStorageSync(AUTH_SESSION_NAME)
  return res ? res.access_token : null
}

module.exports = {
  showLoading,
  hideLoading,
  checkToken,
  saveToken,
  clearToken,
  getToken
}